import { ref, computed } from 'vue'

export default function useShortcut(props, groupRef) {
  const scrollRef = ref(null)
  const shortcuts = computed(() => props.data.map(item => item.title))
  const touch = {}
  const ANCHOR_HEIGHT = 18

  function scrollTo(index) {
    if (isNaN(index)) {
      return
    }
    const realIndex = Math.max(0, Math.min(shortcuts.value.length - 1, index))
    const targetEle = groupRef.value.children[realIndex]
    const scroll = scrollRef.value.scroll
    scroll.scrollToElement(targetEle, 0)
  }
  function onTouchShortcutStart(e) {
    touch.y1 = e.touches[0].pageY
    const targetIndex = parseInt(e.target.dataset.index)
    touch.anchorIndex = targetIndex
    scrollTo(targetIndex)
  }
  function onTouchShortcutMove(e) {
    touch.y2 = e.touches[0].pageY
    const delta = (touch.y2 - touch.y1) / ANCHOR_HEIGHT | 0
    const targetIndex = touch.anchorIndex + delta
    scrollTo(targetIndex)
  }

  return {
    shortcuts,
    scrollRef,
    onTouchShortcutStart,
    onTouchShortcutMove
  }
}
